/**
 * 消息提示工具类
 * 提供统一的成功/失败/警告/信息提示功能
 */

export interface ToastOptions {
  duration?: number
  position?: 'top' | 'bottom' | 'center'
  showClose?: boolean
  customClass?: string
}

export interface MessageOptions extends ToastOptions {
  title?: string
  confirmButtonText?: string
  cancelButtonText?: string
  showCancel?: boolean
}

export type MessageType = 'success' | 'error' | 'warning' | 'info'

class MessageService {
  private container: HTMLElement | null = null
  private toastId = 0

  constructor() {
    this.initContainer()
  }

  private initContainer(): void {
    if (typeof document === 'undefined') return

    this.container = document.createElement('div')
    this.container.id = 'toast-container'
    this.container.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      z-index: 9999;
      pointer-events: none;
    `
    document.body.appendChild(this.container)
  }

  private createToast(type: MessageType, message: string, options: ToastOptions = {}): void {
    if (!this.container) return

    ++this.toastId
    const duration = options.duration ?? 3000
    const showClose = options.showClose ?? false

    const toast = document.createElement('div')
    toast.className = `toast toast-${type} ${options.customClass || ''}`
    toast.style.cssText = `
      background: ${this.getTypeColor(type)};
      color: white;
      padding: 12px 16px;
      border-radius: 6px;
      margin-bottom: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      min-width: 200px;
      max-width: 400px;
      pointer-events: auto;
      transform: translateX(100%);
      transition: all 0.3s ease;
      opacity: 0;
      position: relative;
    `

    const icon = document.createElement('span')
    icon.innerHTML = this.getTypeIcon(type)
    icon.style.fontSize = '16px'

    const text = document.createElement('span')
    text.textContent = message
    text.style.flex = '1'

    toast.appendChild(icon)
    toast.appendChild(text)

    if (showClose) {
      const closeBtn = document.createElement('button')
      closeBtn.innerHTML = '✕'
      closeBtn.style.cssText = `
        background: none;
        border: none;
        color: white;
        cursor: pointer;
        padding: 0;
        font-size: 14px;
        opacity: 0.8;
      `
      closeBtn.onclick = () => this.removeToast(toast)
      toast.appendChild(closeBtn)
    }

    this.container.appendChild(toast)

    // 触发动画
    setTimeout(() => {
      toast.style.transform = 'translateX(0)'
      toast.style.opacity = '1'
    }, 10)

    // 自动移除
    if (duration > 0) {
      setTimeout(() => {
        this.removeToast(toast)
      }, duration)
    }
  }

  private removeToast(toast: HTMLElement): void {
    toast.style.transform = 'translateX(100%)'
    toast.style.opacity = '0'
    setTimeout(() => {
      if (toast.parentNode) {
        toast.parentNode.removeChild(toast)
      }
    }, 300)
  }

  private getTypeColor(type: MessageType): string {
    const colors = {
      success: '#52c41a',
      error: '#ff4d4f',
      warning: '#faad14',
      info: '#1890ff'
    }
    return colors[type]
  }

  private getTypeIcon(type: MessageType): string {
    const icons = {
      success: '✅',
      error: '❌',
      warning: '⚠️',
      info: 'ℹ️'
    }
    return icons[type]
  }

  /**
   * 显示成功消息
   */
  success(message: string, options?: ToastOptions): void {
    this.createToast('success', message, options)
  }

  /**
   * 显示错误消息
   */
  error(message: string, options?: ToastOptions): void {
    this.createToast('error', message, {
      duration: 4000, // 错误消息显示更久
      showClose: true, // 错误消息显示关闭按钮
      ...options
    })
  }

  /**
   * 显示警告消息
   */
  warning(message: string, options?: ToastOptions): void {
    this.createToast('warning', message, options)
  }

  /**
   * 显示信息消息
   */
  info(message: string, options?: ToastOptions): void {
    this.createToast('info', message, options)
  }

  /**
   * 确认对话框
   */
  confirm(message: string, options: MessageOptions = {}): Promise<boolean> {
    return new Promise((resolve) => {
      const modal = document.createElement('div')
      modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10000;
      `

      const dialog = document.createElement('div')
      dialog.style.cssText = `
        background: white;
        border-radius: 8px;
        padding: 24px;
        max-width: 400px;
        width: 90%;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
      `

      const titleEl = document.createElement('h3')
      titleEl.textContent = options.title || '确认操作'
      titleEl.style.cssText = `
        margin: 0 0 16px 0;
        color: #2c3e50;
        font-size: 16px;
      `

      const messageEl = document.createElement('p')
      messageEl.textContent = message
      messageEl.style.cssText = `
        margin: 0 0 24px 0;
        color: #666;
        line-height: 1.5;
      `

      const actions = document.createElement('div')
      actions.style.cssText = `
        display: flex;
        gap: 8px;
        justify-content: flex-end;
      `

      const cancelBtn = document.createElement('button')
      cancelBtn.textContent = options.cancelButtonText || '取消'
      cancelBtn.style.cssText = `
        padding: 8px 16px;
        border: 1px solid #d9d9d9;
        background: white;
        border-radius: 4px;
        cursor: pointer;
        color: #666;
      `
      cancelBtn.onclick = () => {
        document.body.removeChild(modal)
        resolve(false)
      }

      const confirmBtn = document.createElement('button')
      confirmBtn.textContent = options.confirmButtonText || '确认'
      confirmBtn.style.cssText = `
        padding: 8px 16px;
        border: none;
        background: #ff4d4f;
        color: white;
        border-radius: 4px;
        cursor: pointer;
      `
      confirmBtn.onclick = () => {
        document.body.removeChild(modal)
        resolve(true)
      }

      actions.appendChild(cancelBtn)
      actions.appendChild(confirmBtn)
      dialog.appendChild(titleEl)
      dialog.appendChild(messageEl)
      dialog.appendChild(actions)
      modal.appendChild(dialog)
      document.body.appendChild(modal)

      // 点击背景关闭
      modal.onclick = (e) => {
        if (e.target === modal) {
          document.body.removeChild(modal)
          resolve(false)
        }
      }

      // ESC 键关闭
      const handleKeydown = (e: KeyboardEvent) => {
        if (e.key === 'Escape') {
          document.body.removeChild(modal)
          document.removeEventListener('keydown', handleKeydown)
          resolve(false)
        }
      }
      document.addEventListener('keydown', handleKeydown)
    })
  }

  /**
   * 清空所有提示
   */
  clear(): void {
    if (this.container) {
      this.container.innerHTML = ''
    }
  }
}

// 导出单例实例
export const message = new MessageService()

// 导出便捷方法
export const toast = {
  success: (msg: string, options?: ToastOptions) => message.success(msg, options),
  error: (msg: string, options?: ToastOptions) => message.error(msg, options),
  warning: (msg: string, options?: ToastOptions) => message.warning(msg, options),
  info: (msg: string, options?: ToastOptions) => message.info(msg, options),
  confirm: (msg: string, options?: MessageOptions) => message.confirm(msg, options),
  clear: () => message.clear()
}

export default message